<template>
  <div class="table-page-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        placeholder="销售订单号"
        v-model="searchParams.salesOrderNo"
        style="width: 150px"
      />
      <el-input
        placeholder="单据编码"
        v-model="searchParams.billCode"
        style="width: 150px"
      />
      <el-input
        placeholder="物料编码"
        v-model="searchParams.materialCode"
        style="width: 150px"
      />
      <el-input
        placeholder="物料名称"
        v-model="searchParams.materialName"
        style="width: 150px"
      />
      <el-date-picker
        v-model="searchParams.startDate"
        type="date"
        placeholder="开始日期"
        value-format="YYYY-MM-DD"
        style="width: 120px"
      />
      <el-date-picker
        v-model="searchParams.endDate"
        type="date"
        placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="width: 120px"
      />
      <el-button type="primary" @click="searchProducts">搜索</el-button>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" size="small">单据</el-button>
      <el-button
        type="danger"
        @click="handleDelete('批量删除')"
        :disabled="selectedRows.length === 0"
        >批量删除</el-button
      >
      <el-button type="primary" @click="Add" size="small">+ 新增</el-button>
      <!-- 添加点击事件 -->
      <el-button type="danger" size="small" @click="exportToExcel"
        >导出</el-button
      >
    </div>
    <!-- 表格 -->
    <el-table
      @selection-change="handleSelectionChange"
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="materialsBliiId"
        label="序号"
        width="60"
      ></el-table-column>
      <el-table-column prop="planOrderNo" label="计划单号"></el-table-column>
      <el-table-column prop="salesOrderNo" label="销售订单号"></el-table-column>
      <el-table-column prop="orderDeliveryDate" label="订单交期">
        <template #default="scope">
          {{ formatDate(scope.row.orderDeliveryDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="billCode" label="单据编码"></el-table-column>
      <el-table-column prop="billStatus" label="单据状态"></el-table-column>
      <el-table-column prop="businessType" label="业务类型"></el-table-column>
      <el-table-column prop="materialName" label="物料名称"></el-table-column>
      <el-table-column prop="materialCode" label="物料编码"></el-table-column>
      <el-table-column prop="mainUnit" label="主计量"></el-table-column>
      <el-table-column prop="supplymode" label="供应方式"></el-table-column>
      <el-table-column
        prop="productionQuantity"
        label="生产数量"
      ></el-table-column>
      <el-table-column prop="billDate" label="单据日期">
        <template #default="scope">
          {{ formatDate(scope.row.billDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            @click="GetStodto(scope.row.materialCode)"
            >查看</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="
              handleDelete(scope.row.materialsBliiId, [scope.row.materialCode])
            "
            style="margin-left: 5px"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="upd(scope.row.materialCode)"
            style="margin-left: 5px"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="form1.PageIndex"
        v-model:page-size="form1.PageSize"
        :page-sizes="[1, 3, 15, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form1.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      v-model="isDialogVisible"
      title="物料清单明细"
      width="80%"
      :before-close="handleClose"
    >
      <div class="order-info">
        <div class="info-item">
          <span>单据编码:</span>
          <span>{{ order.materialCode }}</span>
        </div>
        <div class="info-item">
          <span>单据日期:</span>
          <span>{{ formatDate(order.billDate) }}</span>
        </div>
        <div class="info-item">
          <span>计划单号:</span>
          <span>{{ order.planOrderNo }}</span>
        </div>
        <div class="info-item">
          <span>业务状态:</span>
          <span>{{ order.businessStatus }}</span>
        </div>
        <div class="info-item">
          <span>业务类型:</span>
          <span>{{ order.businessType }}</span>
        </div>
        <div class="info-item">
          <span>操作员:</span>
          <span>{{ order.operator }}</span>
        </div>
        <div class="info-item">
          <span>销售单号:</span>
          <span>{{ order.salesOrderNo }}</span>
        </div>
        <div class="info-item">
          <span>审核员:</span>
          <span>{{ order.auditor }}</span>
        </div>
        <div class="info-item">
          <span>物料编码:</span>
          <span>{{ order.materialCode }}</span>
        </div>
        <div class="info-item">
          <span>单据状态:</span>
          <span>{{ order.billStatus }}</span>
        </div>
        <div class="info-item">
          <span>计量单位:</span>
          <span>{{ order.measurementUnit }}</span>
        </div>
        <div class="info-item">
          <span>订单交期:</span>
          <span>{{ formatDate(order.orderDeliveryDate) }}</span>
        </div>
        <div class="info-item">
          <span>审核日期:</span>
          <span>{{ formatDate(order.auditDate) }}</span>
        </div>
        <div class="info-item">
          <span>备注信息:</span>
          <span>{{ order.remarks }}</span>
        </div>
        <div class="info-item">
          <span>生产数量:</span>
          <span>{{ order.productionQuantity }}</span>
        </div>
      </div>
      <el-table :data="order1" border class="product-table">
        <el-table-column label="序号" prop="materialsBliiId"></el-table-column>
        <el-table-column label="物料编码" prop="materialCode"></el-table-column>
        <el-table-column label="物料名称" prop="materialName"></el-table-column>
        <el-table-column label="型号规格" prop="modelSpec"></el-table-column>
        <el-table-column label="主计量" prop="mainUnit"></el-table-column>
        <el-table-column
          label="需求数量"
          prop="demandquantity"
        ></el-table-column>
        <el-table-column label="可用量" prop="totalPrice">0</el-table-column>
        <el-table-column label="领用量" prop="unitName">0</el-table-column>
        <el-table-column
          label="领料方式"
          prop="materialmethod"
        ></el-table-column>
        <el-table-column label="供应方式" prop="supplymode"></el-table-column>
      </el-table>
      <div class="button-container">
        <el-button type="primary" @click="confirm">确认</el-button>
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";

const router = useRouter();
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
//分页
const handleSizeChange = (newSize: number) => {
  form1.PageSize = newSize;
  searchProducts();
};
//分页
const handleCurrentChange = (newPage: number) => {
  form1.PageIndex = newPage; // 正确更新页码
  searchProducts();
};
//显示
const searchProducts = () => {
  KongaUrl.get("/wangcong2/api/Log/GetERPMenu", {
    params: {
      PageSize: form1.PageSize,
      PageIndex: form1.PageIndex, // 确保参数名与后端一致
      SalesOrderNo: searchParams.salesOrderNo,
      BillCode: searchParams.billCode,
      MaterialCode: searchParams.materialCode,
      MaterialName: searchParams.materialName,
      StartDate: searchParams.startDate,
      EndDate: searchParams.endDate,
    },
  })
    .then((res) => {
      tableData.value = res.data.data.list;
      // 注意：后端返回的总记录数是 Data.PageCount，但需要根据总记录数计算总页数
      form1.TotalCount = res.data.data.pageCount; // 总记录数
      form1.PageCount = Math.ceil(form1.TotalCount / form1.PageSize); // 前端计算总页数
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};

// 选中的行
// 修改选择处理逻辑（确保ID有效性）
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

// 优化后的删除方法
const handleDelete = async (id: any, materialCode: any = []) => {
  try {
    let ids = [];
    let materialCodes = [];

    if (id === "批量删除") {
      // 批量删除逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning("请至少选择一条记录");
        return;
      }
      ids = selectedRows.value.map((item) => item.materialsBliiId);
      materialCodes = selectedRows.value.map((item) => item.materialCode);

      await ElMessageBox.confirm(
        `确定要删除${selectedRows.value.length}条记录？`,
        "警告",
        { type: "warning" }
      );
    } else {
      // 单条删除逻辑
      ids = [id];
      materialCodes = materialCode;

      await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
        type: "warning",
      });
    }

    // 统一请求处理
    const params = new URLSearchParams();
    params.append("Table", "MaterialsBlii");
    params.append("TableId", "MaterialsBliiId");
    ids.forEach((id) => params.append("Ids", id.toString()));
    materialCodes.forEach((num) => params.append("MaterialCode", num));

    const res = await axios.delete(
      "http://localhost:5027/api/Log/DelsMaterials",
      {
        params: params,
        paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
      }
    );

    if (res.data.code === 500) {
      ElMessage.success(res.data.message);
      searchProducts();
      if (id === "批量删除") {
        selectedRows.value = []; // 清空选择
      }
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略用户取消操作
      ElMessage.error(`操作失败: ${error.message}`);
    }
  }
};

onMounted(() => {
  searchProducts();
});

const formatDate = (dateStr: string) => {
  return dayjs(dateStr).format("YYYY-MM-DD");
};

// 搜索参数
const searchParams = reactive({
  salesOrderNo: "",
  billCode: "",
  materialCode: "",
  materialName: "",
  startDate: "", // 格式示例：'2023-10-01'
  endDate: "",
});
//跳转
const Add = () => {
  router.push({
    path: "/AddBom",
  });
};

// 表格数据
const tableData = ref([]);
//跳转修改
const upd = (materialCode: string) => {
  router.push({
    path: "/UpdateBom",
    query: {
      materialCode: materialCode,
    },
  });
};
//明细
//关闭弹框
const closeDialog = () => {
  isDialogVisible.value = false;
};
const confirm = () => {
  // 这里可以添加确认后的逻辑，比如关闭弹窗并进行数据提交等操作
  isDialogVisible.value = false;
};
const handleClose = () => {
  // 关闭弹窗前的逻辑处理
  closeDialog();
};
const order = ref([]);
const order1 = ref([]);
const isDialogVisible = ref(false);
//明细
const GetStodto = (materialCode: string) => {
  isDialogVisible.value = true;
  KongaUrl.get(
    `/wangcong2/api/Log/EditBillInfo?MaterialCode=${materialCode}`
  ).then((res) => {
    order.value = res.data.data[0];
    console.log(order.value);
    // 获取入库单产品信息
    KongaUrl.get(
      `/wangcong2/api/Log/EditMaterialsBlii?MaterialCode=${materialCode}`
    ).then((res) => {
      order1.value = res.data.data;
      console.log(order1.value);
    });
  });
};
//导出
// 提取选中行的 materialsBliiId（关键修改：从 billCode 改为 materialsBliiId）
const exportToExcel = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要导出的记录");
    return;
  }

  const params = new URLSearchParams();
  params.append("PageSize", form1.PageSize.toString());
  params.append("PageIndex", form1.PageIndex.toString());
  params.append("SalesOrderNo", searchParams.salesOrderNo);
  params.append("BillCode", searchParams.billCode);
  params.append("MaterialCode", searchParams.materialCode);
  params.append("MaterialName", searchParams.materialName);
  params.append("StartDate", searchParams.startDate);
  params.append("EndDate", searchParams.endDate);
  selectedRows.value.forEach((row) => {
    params.append("Ids", row.materialsBliiId.toString());
  });

  KongaUrl.get("/wangcong2/api/Log/ExportOrderListToExcel", {
    params: params,
    paramsSerializer: (params) => params.toString(), // 确保参数正确序列化
    responseType: "blob",
  })
    .then((response) => {
      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = "物料清单数据.xlsx";
      link.click();
      window.URL.revokeObjectURL(url);
    })
    .catch((error) => {
      ElMessage.error(`导出失败: ${error.message}`);
    });
};
</script>

<style scoped>
.table-page-container {
  padding: 10px;
}
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}
.action-buttons {
  margin-bottom: 10px;
}
.pagination-container {
  text-align: center;
  margin-top: 10px;
}
</style> 
<style scoped>
.order-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}
.info-item {
  width: 300px;
}
.product-table {
  width: 100%;
  margin-bottom: 20px;
}
.button-container {
  text-align: right;
}
</style>   